<?php
$servername = "127.0.0.1";
$username = "web";
$password = "123456";
$dbname = "web2022_com";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
//接收用户的输入
if (!empty($_REQUEST['username']) &&
    !empty($_REQUEST['pwd']) &&
    !empty($_REQUEST['avator']) &&
    !empty($_REQUEST['sex'])
) {
    //检查用户名是否被占用
    $usersql = "select * from user where username='" . $_REQUEST['username'] . "' limit 1";
    $result = $conn->query($usersql);
    $row = $result->fetch_row();
    if ($row) {
        echo json_encode(['code' => 401, 'msg' => '用户名已存在']);
        exit;
    }
    $addsql = "INSERT INTO `web2022_com`.`user`(`username`, `password`, `avator`,`sex`) VALUES ('" . $_REQUEST['username'] . "', '" . md5($_REQUEST['pwd']) . "', '" . $_REQUEST['avator'] . "'," . $_REQUEST['sex'] . ")";
    $result = $conn->query($addsql);
    if ($result) {
        echo json_encode(['code' => 200, 'msg' => '注册 成功']);
    } else {
        echo json_encode(['code' => -1, 'msg' => '插入 错误']);
    }
} else {
    echo json_encode(['code' => -1, 'msg' => 'register error']);
}
$conn->close();
